package com.sinaapp.gavinzhang.GSpider.http.servlet;

import com.sinaapp.gavinzhang.GSpider.common.FileUtil;
import com.sinaapp.gavinzhang.GSpider.common.IpUtil;
import com.sinaapp.gavinzhang.GSpider.common.ServletUtil;
import com.sinaapp.gavinzhang.GSpider.config.PageProcessorConfig;
import com.sinaapp.gavinzhang.GSpider.http.annotation.ServletClass;
import com.sinaapp.gavinzhang.GSpider.management.RegistrationCenter;
import com.sinaapp.gavinzhang.GSpider.management.Stub;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * @author gavin
 * @version 1.0
 * @date 2016/4/5
 * @description 首页
 */
@ServletClass(requestName = "/")
public class IndexServlet extends HttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(IndexServlet.class);

    public static PageProcessorConfig pageProcessorConfig;
    public static String trueinitUrl;
    private static String initUrl = "http://www.zhihu.com/explore";
    private static String regex = "http://www.zhihu.com/question/[0-9]+";
    private static int timeout = 2000;
    private static int sleepTime = 1000;
    private static int waitTime = 1000;
    private static String file = "com.sinaapp.gavinzhang.GSpider.DefaultPageProcessor";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.addHeader("Content-Type", "text/html;charset=utf-8");
        resp.addHeader("Server", "GS1.1");

        //测试环境能用  打成jar包就不能用了
//        URL base = ClassLoader.getSystemResource("");
//        logger.debug(base.toString());
//        File file = new File(base.getPath()+"/html/index.html");
//        if (file.exists()){
//            PrintWriter writer = resp.getWriter();
//            byte[] byteArray = FileUtil.readBytes(new FileInputStream(file));
//            String index = new String(byteArray,"UTF8");
//            index = index.replace("${centerIp}", IpUtil.getRealIp());
//            index = index.replace("${centerPort}", String.valueOf(RegistrationCenter.DEFAULT_PORT));
//            writer.write(index);
//            writer.flush();
//            writer.close();
//        }
        if (req.getRequestURI().startsWith("/bootstrap")) {
            readFile(req, resp);
            return;
        }
        if (!req.getRequestURI().endsWith("/")) {
            return;
        }

        if (req.getQueryString() != null && req.getQueryString().contains("config")) {
            readHtml(req, resp, "html/config.html");
            return;
        }

        readHtml(req, resp, "html/index.html");
    }

    /**
     * 从jar包读取内容
     * @param req
     * @param resp
     * @param s
     * @throws ServletException
     * @throws IOException
     */
    private void readHtml(HttpServletRequest req, HttpServletResponse resp, String s) throws ServletException, IOException {
        PrintWriter writer = resp.getWriter();
        String index = ServletUtil.readHtml(s, "UTF8");
        index = index.replace("${centerIp}", ConfigServlet.centerIp);
        index = index.replace("${centerPort}", String.valueOf(RegistrationCenter.DEFAULT_PORT));
        if (pageProcessorConfig == null){
            index = index.replace("${initUrl}",initUrl);
            index = index.replace("${regex}",regex);
            index = index.replace("${timeout}",String.valueOf(timeout));
            index = index.replace("${sleepTime}",String.valueOf(sleepTime));
            index = index.replace("${waitTime}",String.valueOf(waitTime));
            index = index.replace("${file}",file);
        }else {
            index = index.replace("${initUrl}",trueinitUrl);
            String regex = "";
            for (Pattern p :pageProcessorConfig.getPatterns()){
                regex += p.toString()+";";
            }
            index = index.replace("${regex}",regex);
            index = index.replace("${timeout}",String.valueOf(pageProcessorConfig.getTimeout()));
            index = index.replace("${sleepTime}",String.valueOf(pageProcessorConfig.getSleepTime()));
            index = index.replace("${waitTime}",String.valueOf(pageProcessorConfig.getWaitTime()));
            index = index.replace("${file}",pageProcessorConfig.getPageProcessor().getClass().getName());
        }
        writer.write(index);
        writer.flush();
        writer.close();
    }

    /**
     * 读取文件内容
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void readFile(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (req.getHeader("Accept") != null) {
            String accept = req.getHeader("Accept");
            if (accept.contains(",")) {
                resp.setHeader("Content-Type", accept.split(",")[0] + ";charset=utf-8");
            } else {
                resp.setHeader("Content-Type", accept + ";charset=utf-8");
            }
        }
        PrintWriter writer = resp.getWriter();
        String index = ServletUtil.readHtml("html/" + req.getRequestURI(), "UTF8");
        writer.write(index);
        writer.flush();
        writer.close();
    }


    public static void main(String[] args) {
        Map<Object, Object> map = System.getProperties();
        for (Object o : map.keySet()) {
            System.out.println(o + "|====|" + map.get(o));
        }
        URL base = ClassLoader.getSystemResource("");
        File file = new File(base.getPath() + "/html/index.html");
        logger.info(file.getAbsolutePath());
        logger.info("" + file.exists());

    }
}
